package de.unibielefeld.msp.zusatzstoffe.utility;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;



/**
 * @author Rico Magnucki (rmagnuck@techfak.uni-bielefeld.de)
 */
public class ServiceConsumer {

    private static DefaultHttpClient client;
    private static SchemeRegistry registry;
    private static HttpParams params;
    private static ThreadSafeClientConnManager cm;


    public static boolean checkTrueState() {
        if (client == null) {
            return false;
        }else {
            return true;
        }
    }

    public static void closeExpiredConnections() {
        getClient().getConnectionManager().closeExpiredConnections();
    }

    /**
     * Erstellt bzw Übergibt den Einzigen HttpClienten.
     *
     * @return den Clienten
     */
    public static final HttpResponse execute(HttpGet request) {
        HttpResponse response = null;
        try {
            response = getClient().execute(request);
            return response;
        } catch (ClientProtocolException e) {
            if (e instanceof HttpResponseException){
                HttpResponseException hte = (HttpResponseException) e;
                System.err.println(hte);
            }
            e.printStackTrace();
            handelServerComError();
        } catch (IOException e) {
            e.printStackTrace();
            handelServerComError();
        }
        return null;
    }

    /**
     * Erstellt bzw Übergibt den Einzigen HttpClienten.
     *
     * @return den Clienten
     */
    public static final HttpResponse execute(HttpPost response) {
        try {
            return getClient().execute(response);
        } catch (ClientProtocolException e) {
            if (e instanceof HttpResponseException){
                System.out.println("ServiceConsumer in der HTTP Exception ..");
                System.err.println(e);
            }
            e.printStackTrace();
            handelServerComError();
        } catch (IOException e) {
            e.printStackTrace();
            handelServerComError();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Erstellt bzw Übergibt den Einzigen HttpClienten.
     *
     * @return den Clienten
     */
    private static final DefaultHttpClient getClient() {
        if (client == null) {// activieren

            registry = new SchemeRegistry();
            registry.register(new Scheme("http",
                    PlainSocketFactory.getSocketFactory(), 80));

            params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
            HttpProtocolParams.setUseExpectContinue(params, true);

            cm = new ThreadSafeClientConnManager(params, registry);

            client = new DefaultHttpClient(cm, params);
            client.getCredentialsProvider().setCredentials(
                    new AuthScope(null, -1),
                    new UsernamePasswordCredentials(Constants.SERVER_USERNAME,
                            Constants.SERVER_PASSWORD));

        }
        return client;
    }

    private static void handelServerComError() {
        // TODO HANDEL ERRORS WHILE COM WITH SERVER!

    }

    /**
     * Public Constructor.
     */
    public ServiceConsumer() {
        super();
    }

    public void close() {
        client = null;

    };

}
